from ldap3 import Server, Connection, ALL, SUBTREE
from config import Config

# corp
conf = Config()

HOST = conf.LDAP_HOST
BIND_DN = conf.LDAP_BIND_DN
BIND_PASS = conf.LDAP_BIND_PASS
USE_SSL = conf.LDAP_USE_SSL


def get_group_users(group_name):
    s = Server(HOST, get_info=ALL, use_ssl=USE_SSL)
    c = Connection(s, user=BIND_DN, password=BIND_PASS, auto_bind=True)
    result = c.search(
        search_base=conf.LDAP_GROUP_SEARCH_BASE,
        search_filter='(cn={})'.format(group_name),
        search_scope=SUBTREE,
        attributes=['uniqueMember'],
        paged_size=100
    )
    if not result:
        return []
    return c.response[0]['attributes']['uniqueMember']


def ldap_login(username, password):
    s = Server(HOST, get_info=ALL, use_ssl=USE_SSL)
    c = Connection(s, user=BIND_DN, password=BIND_PASS, auto_bind=True)

    # 1 检查LDAP用户密码
    user_result = c.search(
        search_base=conf.LDAP_USER_SEARCH_BASE,
        search_filter='({}={})'.format(conf.LDAP_USER_NAME_PARAM, username),
        search_scope=SUBTREE,
        attributes=['cn'],
        paged_size=10
    )
    if not user_result:
        print('{} 用户不在LDAP中'.format(username))
        return ''

    dn = c.response[0]['dn']
    cn = c.response[0]['attributes']['cn'][0]

    try:
        Connection(s, user=dn, password=password, auto_bind=True)
        print("uid:{} cn:{} LDAP密码验证成功".format(username, cn))
    except Exception as e:
        print("uid:{} cn:{} LDAP密码验证失败".format(username, cn))
        print(e)
        return ''

    # 2 检查用户是否在组里
    group_name = conf.LDAP_GROUP_CN
    group_result = c.search(
        search_base=conf.LDAP_GROUP_SEARCH_BASE,
        search_filter='(cn={})'.format(group_name),
        search_scope=SUBTREE,
        attributes=['uniqueMember'],
        paged_size=100
    )
    members = c.response[0]['attributes']['uniqueMember'] if group_result else []
    if dn not in members:
        print('{} 用户不在LDAP组 {} 中'.format(username, group_name))
        return ''

    # 3 返回用户名
    return cn

